<script lang="ts">
	import { Any } from '$lib/api/proto/google/protobuf/any';
	import { ChoiceAnswer, ChoiceQuestion } from '$lib/api/proto/resource_exam_type_api';
	import { appStore } from '$lib/stores/app.svelte';
	import { userStore } from '$lib/stores/user.svelte';
	import { callApi } from '$lib/utils/call_utils';
	import { roadmapStore } from '../../store.svelte';

	interface Props {
		questionId: string;
		question: Any;
		answer: Any;
	}
	let props: Props = $props();

	const question = $derived(Any.unpack(props.question, ChoiceQuestion));
	const multiChoice = $derived(
		Any.unpack(props.question, ChoiceQuestion).choiceList.filter((item) => item.rightAnswer)
			.length > 1
	);

	let lableList = $state(
		props.answer.typeUrl.endsWith('.ChoiceAnswer')
			? Any.unpack(props.answer, ChoiceAnswer).lableList
			: []
	);

	async function setAnswer() {
		if (userStore.userSession == null || roadmapStore.selectNodeIdList.length == 0) {
			return;
		}
		await callApi(
			appStore.resourceExamApiClient.setStateByRoadmap({
				sessionId: userStore.userSession,
				roadmapId: roadmapStore.roadmapId,
				nodeId: roadmapStore.selectNodeIdList[0],
				questionId: props.questionId,
				answer: Any.pack(
					{
						lableList: lableList
					},
					ChoiceAnswer
				)
			}).response
		);
		roadmapStore.resourceStateVersion += 1;
	}

	$effect(() => {
		lableList = props.answer.typeUrl.endsWith('.ChoiceAnswer')
			? Any.unpack(props.answer, ChoiceAnswer).lableList
			: [];
	});
</script>

<div class="prose max-w-none p-2 w-full">
	<h3>问题:{question.question}</h3>
	<h4>选项:</h4>
	{#each question.choiceList as choice}
		<div class="flex gap-2">
			{#if multiChoice}
				<input
					type="checkbox"
					checked={lableList.includes(choice.label)}
					class="checkbox"
					disabled={roadmapStore.roadmapMode == 'view'}
					onchange={(e) => {
						if (e.currentTarget.checked) {
							if (!lableList.includes(choice.label)) {
								lableList.push(choice.label);
								setAnswer();
							}
						} else {
							lableList = lableList.filter((item) => item != choice.label);
							setAnswer();
						}
					}}
				/>
			{:else}
				<input
					type="radio"
					name={props.questionId}
					class="radio"
					disabled={roadmapStore.roadmapMode == 'view'}
					checked={lableList.includes(choice.label)}
					onchange={(e) => {
						if (e.currentTarget.checked) {
							lableList = [choice.label];
							setAnswer();
						}
					}}
				/>
			{/if}
			<span>{choice.label}:</span>
			<span>{choice.value}</span>
		</div>
	{/each}
	{#if roadmapStore.roadmapMode == 'view'}
		<h4>正确答案:</h4>
		<div class="flex gap-2">
			{#each question.choiceList as choice}
				{#if choice.rightAnswer}
					<span>{choice.label}</span>
				{/if}
			{/each}
		</div>
	{/if}
</div>
